package com.auth.system.service.impl;

import com.alibaba.fastjson.JSON;
import com.auth.config.exception.AuthException;
import com.auth.system.dao.OauthClientDetailsMapper;
import com.auth.system.entity.build.OauthClientDetailsEntity;
import com.auth.system.entity.dto.OauthClientDetailsDto;
import com.auth.system.service.AuthService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class AuthServiceImpl implements AuthService {


    @Autowired
    private OauthClientDetailsMapper oauthClientDetailsMapper;


    @Override
    public OauthClientDetailsDto getAuthenticationProperty(String ip){
        LambdaQueryWrapper<OauthClientDetailsEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(OauthClientDetailsEntity::getAdditionalInformation,ip);
        OauthClientDetailsEntity oauthClientDetailsEntity = oauthClientDetailsMapper.selectOne(queryWrapper);
        if (null == oauthClientDetailsEntity){
             throw new AuthException("未认证");
        }
        OauthClientDetailsDto clientDetailsDto = new OauthClientDetailsDto();
        BeanUtils.copyProperties(oauthClientDetailsEntity,clientDetailsDto);
        OauthClientDetailsDto oauthClientDetailsDto =   JSON.parseObject(oauthClientDetailsEntity.getAdditionalInformation(),OauthClientDetailsDto.class);
        clientDetailsDto.setClientSecret(oauthClientDetailsDto.getClientSecret());
        if (clientDetailsDto.getAuthorizedGrantTypes().indexOf("password") != -1){
            clientDetailsDto.setGrantTypePassword("password");
        }
        if (clientDetailsDto.getAuthorizedGrantTypes().indexOf("refresh_token") != -1){
            clientDetailsDto.setGrantTypeRefreshToken("refresh_token");
        }

        return clientDetailsDto;
    }
}
